<template>
  <div>
    <h1>管理员信息</h1>
    <el-form :inline="true" :model="fromData" class="demo-form-inline">
      <!-- 添加手机号输入框 -->
      <el-form-item label="手机号">
        <el-input v-model="fromData.phone" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSelect">查询</el-button>
      </el-form-item>
      <el-form-item>
          <el-button type="success" @click="addManager">新增管理员</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dangqianyeData"
      style="width: 100%">
      <!-- <el-table-column
        label="管理员ID" align='center' prop="id"
        width="180">
      </el-table-column> -->
      <el-table-column
        label="管理员头像" align='center'>
        <template slot-scope="scope">
          <el-image v-if="isDataLoaded"
                    style="width: 50px; height: 50px"
                    :src="scope.row.avatar"
                    fit="cover"
                    :preview-src-list="[scope.row.avatar]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        label="管理员账号" align='center' prop="account">
      </el-table-column>
      <el-table-column
        label="管理员姓名" align='center' prop="name">
      </el-table-column>
      <el-table-column
        label="管理员手机号" align='center' prop="phone">
      </el-table-column>
      <el-table-column
        label="管理员邮箱" align='center' prop="email">
      </el-table-column>
      <el-table-column align='center' label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-if="isDataLoaded">
      <el-pagination
        layout="prev, pager, next"
        @current-change='changepage'
        :page-count="maxPage"
        :total="managerList.length">
      </el-pagination>
    </div>
    <!-- 新增管理员的弹窗 -->
    <el-dialog title="新增管理员" :visible.sync="dialogVisible" width="40%">
      <el-form ref="addManagerForm" :model="newManager" label-width="80px" label-position="top">
        <el-form-item label="管理员账号">
          <el-input v-model="newManager.account" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="管理员姓名">
          <el-input v-model="newManager.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="管理员手机号">
          <el-input v-model="newManager.phone" autocomplete="off" @input="validatePhone(newManager.phone)"></el-input>
        </el-form-item>
        <el-form-item label="管理员邮箱">
          <el-input v-model="newManager.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="管理员密码">
          <el-input v-model="newManager.pwd" type="password" autocomplete="new-pwd"></el-input>
        </el-form-item>
        <el-form-item label="管理员头像">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8081/img/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="newManager.avatar" :src="newManager.avatar" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeAddManagerDialog">取 消</el-button>
        <el-button type="primary" @click="submitAddManager">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑管理员的弹窗 -->
    <el-dialog title="编辑管理员" :visible.sync="dialogEditVisible" width="40%">
      <el-form ref="editManagerForm" :model="editManager" label-width="80px" label-position="top">
        <el-form-item label="管理员账号">
          <el-input v-model="editManager.account"></el-input>
        </el-form-item>
        <el-form-item label="管理员姓名">
          <el-input v-model="editManager.name"></el-input>
        </el-form-item>
        <el-form-item label="管理员手机号">
          <el-input v-model="editManager.phone"></el-input>
        </el-form-item>
        <el-form-item label="管理员邮箱">
          <el-input v-model="editManager.email"></el-input>
        </el-form-item>
        <el-form-item label="管理员密码">
          <el-input v-model="editManagerPwd" type="password" autocomplete="new-pwd"></el-input>
        </el-form-item>
        <el-form-item label="管理员头像">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8081/img/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="newManager.avatar" :src="newManager.avatar" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogEditVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditManager">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { computed } from 'vue';
import axios from 'axios';
import { baseUrl } from '../store/baseUrl';

export default {
  name: 'Manager',
  data () { 
    return {
      fromData: {
        name: '',
        type: ''
      },

      managerList: [],
      dangqianpage: 1,
      maxPage: 0,
      isDataLoaded: false,
      dialogVisible: false, // 控制新增管理员对话框的显示状态
      newManager: { // 存储新增管理员的信息
        account: '',
        name: '',
        phone: '',
        email: '',
        pwd: '', // 添加密码字段
        avatar: null // 添加头像字段
      },
      rules: {
        phone: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          { validator: this.validatePhone, trigger: 'blur' }
        ]
      },
      isPhoneValid: true,
      editManager: {}, // 用于存储编辑管理员的信息
      editManagerPwd: '', // 新密码
      dialogEditVisible: false, // 控制编辑管理员对话框的显示状态
      phone: '',// 在 Vue.js 组件的数据定义中添加手机号属性
      imageUrl:''
    };
  },
  computed: {
    dangqianyeData() {
      const qishi = (this.dangqianpage - 1) * 10;
      return this.managerList.slice(qishi, qishi + 10);
    },
    isDataLoaded() {
      return this.managerList.length > 0;
    },
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      axios.get("http://localhost:8081/manager/list")
        .then(response => {
          this.managerList = response.data.data;
          this.managerList.forEach(user => {
            user.avatar = `http://localhost:8081${user.avatar}`;
          });
          this.maxPage = Math.ceil(this.managerList.length / 10);
          this.isDataLoaded = true;
        })
        .catch(error => {
          console.error('There was an error!', error);
        });
    },
    onSelect() {
      console.log('查询手机号:', this.fromData.phone);
      // 调用后端模糊查询接口
      this.searchByPhone();

    },

    validatePhone(phone) {
      const phoneRegex = /^1[3-9]\d{9}$/;
      this.isPhoneValid = phoneRegex.test(phone);
      return this.isPhoneValid;
    },
    beforeAvatarUpload(file) {
      // 只返回 true，因为我们将在点击“确定”时上传文件
      return true;
    },
    // 新增 searchByPhone 方法
    searchByPhone() {
      axios.get("http://localhost:8081/manager/searchByPhone", {
        params: {
          phone: this.fromData.phone
        }
      })
      .then(response => {
        this.managerList = response.data.data;
        this.managerList.forEach(user => {
          user.avatar = `http://localhost:8081${user.avatar}`;
        });
        this.maxPage = Math.ceil(this.managerList.length / 10);
        this.isDataLoaded = true;
      })
      .catch(error => {
        console.error('There was an error searching for the manager by phone!', error);
      });
    },
    handleEdit (index, row) {
      this.editManager = { ...row }; // 复制管理员信息
      this.dialogEditVisible = true; // 显示编辑对话框
    },
    handleDelete (index, row) {
      // 确认用户是否真的想删除
      this.$confirm('此操作将永久删除该管理员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送请求
        axios.post(`http://localhost:8081/manager/removeById/${row.id}`)
          .then(response => {
            // 删除成功后，刷新数据
            this.fetchData();
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          })
          .catch(error => {
            console.error('There was an error deleting the manager!', error);
            this.$message({
              type: 'error',
              message: '删除失败!'
            });
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    changepage(page){
      this.dangqianpage = page;
    },
    handleAvatarSuccess(res, file) {
      // 使用后端返回的路径作为图像的URL
      this.imageUrl = res.data;
      // 添加 avatar 字段到 formLabelAlign 对象中，使用后端返回的数据
      this.newManager.avatar = `http://localhost:8081${this.imageUrl}`;
    },
      beforeAvatarUpload(file) {
        this.fromData.avatar = file.name;
        const isPNG = file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isPNG) {
          this.$message.error('上传头像图片只能是 PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isPNG && isLt2M;
      },
    addManager() {
      // 显示新增管理员的对话框
      this.dialogVisible = true;
    },
    submitAddManager() {
      if (!this.validatePhone(this.newManager.phone)) {
        this.$message.error('手机号码无效，请输入正确的11位手机号码');
        return;
      }
      this.newManager.avatar=this.imageUrl
      // 提交新增管理员表单
      axios.post("http://localhost:8081/manager/add", this.newManager)
        .then(response => {
          // 如果成功，刷新管理员列表
          this.fetchData();
          // 关闭对话框
          this.closeAddManagerDialog();
          console.log("成功")
        })
        .catch(error => {
          console.error('There was an error adding the manager!', error);
        });
    },
    closeAddManagerDialog() {
      // 清空表单
      this.newManager = {
        account: '',
        name: '',
        phone: '',
        email: '',
        avatar:'',
      };
      // 关闭对话框
      this.dialogVisible = false;
    },
    submitEditManager() {
      // 提交编辑管理员表单
      const updatedManager = { ...this.editManager, pwd: this.editManagerPwd };
      updatedManager.avatar=this.imageUrl;
      axios.post("http://localhost:8081/manager/modifyById", updatedManager)
        .then(response => {
          // 如果成功，刷新管理员列表
          this.fetchData();
          // 关闭对话框
          this.dialogEditVisible = false;
          console.log("成功")
        })
        .catch(error => {
          console.error('There was an error editing the manager!', error);
        });
    },
    handleEditAvatarUploadSuccess(response, file, fileList) {
      if (response.success) {
        this.editManager.avatar = this.imageUrl; // 更新头像URL
        console.log(this.editManager.avatar)
      } else {
        console.error('上传失败', response);
      }
    },
  }
}
</script>

<style scoped>
  .el-table {
    margin: auto;
    margin-top: 20px;
  }
  .el-pagination{
    text-align: center;
    margin-top: 20px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  
</style>
